<!--
 	* @author  gaohailan
-->
<template>
  <div id="workerStudyEdit">
    <div class="main-title">受理合理化建议</div>
    <el-form
      v-loading="formloading"
      ref="baseForm"
      :model="baseForm"
      :rules="rules"
      class="dataForm"
      label-position="right"
      label-width="140px"
    >
      <el-form-item label="改善名称" prop="name">
        <el-input style="width: 90%" disabled v-model="baseForm.name" />
      </el-form-item>
      <el-form-item label="选择类别" prop="category">
        <el-select v-model="baseForm.category">
          <el-option key="1" value="1" label="生产经营" />
          <el-option key="2" value="2" label="管理" />
          <el-option key="3" value="3" label="安全" />
          <el-option key="4" value="4" label="职工教育" />
          <el-option key="5" value="5" label="党建及精神文明建设" />
          <el-option key="6" value="6" label="生活福利" />
        </el-select>
      </el-form-item>
      <el-form-item label="建议人" prop="advicePeople">
        <el-input style="width: 90%" disabled v-model="baseForm.advicePeople" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input style="width: 90%" disabled v-model="baseForm.phoneNumber" />
      </el-form-item>
      <el-form-item label="所在单位及部门" prop="jobs">
        <el-input style="width: 90%" disabled v-model="baseForm.jobs" />
      </el-form-item>
      <el-form-item label="问题现状" prop="problemActuality">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
          disabled
          v-model="baseForm.problemActuality"
        ></el-input>
      </el-form-item>
      <el-form-item label="改善方案" prop="improvedSolution">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
          disabled
          v-model="baseForm.improvedSolution"
        ></el-input>
      </el-form-item>
      <el-form-item label="图片补充" prop="improvedSolution">
        <div class="custom-uploader">
          <div
            v-for="(item, index) in picture"
            :key="index"
            style="margin-bottom: 10px; display: flex; align-items: center"
          >
            <img v-if="item != ''" :src="view + item" class="avatar" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="是否受理" prop="acceptState">
        <el-radio-group
          v-model="baseForm.acceptState"
          @change="agreeChange"
        >
          <el-radio :label="4">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 不受理 -->
      <el-form-item v-if="examineState == 0" label="原因" prop="reason">
        <el-input
          type="textarea"
          :rows="3"
          :disabled="checktrue"
          placeholder="请输入内容"
          v-model="baseForm.reason"
        ></el-input>
      </el-form-item>
      <!-- 受理 -->
      <el-form-item
        v-if="examineState !== 0"
        label="受理人"
        prop="examinePeople"
      >
        <el-radio-group
          v-model="baseForm.examinePeople"
          :disabled="checktrue"
          @change="agreePeopleChange"
        >
          <el-radio :label="0">本人</el-radio>
          <el-radio :label="1">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 其他人受理 -->
      <el-form-item
        v-if="examineState == 2"
        label="选择受理人"
        prop="suggestName"
      >
        <div
          v-for="(item, index) in dialogMultipleSelection"
          :key="item.id"
          class="select-data"
        >
          {{ item.realName
          }}<i class="el-icon-close" @click="removeUser(item, index)" />
        </div>
        <div class="selectbtn" @click="addUser">选择用户</div>
      </el-form-item>
      <!--本人受理 -->
      <el-form-item
        v-if="examineState == 1"
        label="受理情况"
        prop="acceptSituation"
      >
        <el-input
          type="textarea"
          :rows="3"
          :disabled="checktrue"
          placeholder="请输入内容"
          v-model="baseForm.acceptSituation"
        ></el-input>
      </el-form-item>
      <el-form-item
        v-if="examineState == 1"
        label="受理信息补充"
        prop="indexUrl"
      >
        <div class="custom-uploader">
          <div
            v-for="(item, index) in infoUrlArr"
            :key="index"
            style="margin-bottom: 10px; display: flex; align-items: center"
          >
            <img :src="view + item" class="avatar" />
            <el-button
              type="primary"
              v-if="!checktrue"
              style="height: 28px; margin-left: 10px"
              size="mini"
              @click="delInfoUrl(item, index)"
              >删除</el-button
            >
          </div>

          <template v-if="!checktrue">
            <div class="icon-wrap" @click="imgcropIndexShow = true">
              <i class="el-icon-plus avatar-uploader-icon" />
            </div>
          </template>
          <p v-if="!checktrue" class="size-tip">建议上传尺寸为：690px*320px</p>
        </div>
        <image-cropper
          v-if="imgcropIndexShow && !checktrue"
          :key="imagecropperKey"
          :width="690"
          :height="320"
          :url="uploadaction"
          :headers="uploadHeaders"
          lang-type="zh"
          :no-circle="true"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </el-form-item>
      <!-- 集团 -->
      <el-form-item
        v-if="userType == '平台管理员' && this.baseForm.acceptState == 1"
        label="是否公示"
      >
        <!-- <el-select v-model="baseForm.publicity" placeholder="请选择">
          <el-option key="0" :value="0" label="否" />
          <el-option key="1" :value="1" label="是" />
        </el-select> -->
        <el-radio-group
          v-model="baseForm.publicity"
        >
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="common-btns">
      <el-button style="padding: 8px 30px" @click="cancel">取消</el-button>
      <el-button style="padding: 8px 30px" type="primary" @click="getgo()"
        >确定
      </el-button>
      <el-button
        style="padding: 8px 30px"
        v-if="this.examineState != 0 && this.acceptStates == 0"
        type="primary"
        @click="updateDatass()"
        >本单位无法受理转集团受理
      </el-button>
      
    </div>
    <!-- 选择受理人 -->
    <el-dialog
      :title="'选择受理人'"
      :visible.sync="dialogFormVisibleUser"
      center
      width="750px"
      top="10vh"
    >
      <div class="tablewrap" style="height: 100%; overflow-y: auto">
        <div class="search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">用户名称</div>
                <el-input
                  v-model="dialogsearch.userName"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入用户名搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">真实姓名</div>
                <el-input
                  v-model="dialogsearch.realName"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入真实姓名搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">联系电话</div>
                <el-input
                  v-model="dialogsearch.phoneNumber"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入联系电话搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">所属企业</div>
                <el-input
                  v-model="dialogsearch.orgName"
                  style="width: 90%"
                  class="filter-item"
                  placeholder="请输入所属企业搜索"
                />
              </div>
            </el-col>
          </el-row>
          <el-col :span="24" style="margin-bottom: 10px">
            <el-button
              v-waves
              class="search-btn"
              type="primary"
              @click="dialoghandleFilter"
              >搜索</el-button
            >
          </el-col>
        </div>
        <el-table
          ref="rolemantable"
          v-loading="dialogListLoading"
          :header-cell-style="rowClass"
          :data="dialogList"
          class="tableScope"
          style="width: 100%"
          @selection-change="dialogHandleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="userName"
            label="用户名称"
            show-overflow-tooltip
            width="250"
          />
          <el-table-column
            prop="realName"
            label="真实姓名"
            show-overflow-tooltip
          />
          <el-table-column
            prop="phoneNumber"
            label="联系电话"
            show-overflow-tooltip
            width="180"
          />
          <el-table-column
            prop="status"
            label="状态"
            width="80"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span>{{ scope.row.status == 0 ? "启用" : "停用" }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn-pagion fix">
          <pagination
            v-show="dialogTotal > 0"
            :total="dialogTotal"
            :page.sync="dialogListQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getDialogList"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="dialogFormVisibleUser = false"
          >取消</el-button
        >
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="insertUser()"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getUserList } from "@/api/usermanage/enterpriseuser";
// import {
//   SuggestActiveInsert,
//   acceptisnoperson,
//   acceptsnopersong,
//   suggestPlanUpdates,
// } from "@/api/reasonable/index";
// import { getUserInfo } from "@/api/login";
import { getToken } from "@/utils/auth";
import ImageCropper from "@/components/ImageCropper";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import waves from "@/directive/waves"; // Waves directive

export default {
  name: "improveEdit",
  components: { ImageCropper, Pagination },
  directives: { waves },
  data() {
    return {
      userType:localStorage.getItem('userTypeRemark'),
      rules:{
        acceptState: [
            { required: true, message: '请选择是否受理', trigger: 'change' },
          ],
      },
      checkType:'',
      checktrue: false,
      acceptStates: "0",
      examineState: 1,
      view: "/API-RESOURCE/webView?fid=",
      state: "create",
      formloading: false,
      imagecropperKey: 0,
      id: "",
      imgcropIndexShow: false, //封面上传窗口
      infoUrlArr: [], // 图片
      baseForm: {
        id: "",
        name: "",
        category: "",
        advicePeople: "",
        phoneNumber: "",
        jobs: "",
        problemActuality: "",
        improvedSolution: "",
        type: 0,
        strTime: "",
        endTime: "",
        state: 0,
        acceptState: 4,
        examinePeople:0,
        fid: "", // 图片
        publicity: "", //是否公示
        acceptSituation: "", //受理情况
        reason: "", //原因
      },
      picture: [],
      userInfo: {},
      uploadaction: "/API-RESOURCE/upload/uploadFile",
      uploadHeaders: { ttsxAuthToken: getToken() },
      view: "/API-RESOURCE/webView?fid=",
      dialogMultipleSelection: "",
      dialogFormVisibleUser: false,
      dialogListLoading: false,
      dialogList: [],
      acceptInformationSupplement: [],
      dialogTotal: 0,
      dialogListQuery: {
        page: 1,
        limit: 8,
      },
      listQuery: {
        page: 1,
        limit: 10,
        userName: "",
      },
      dialogsearch: {
        userName: "",
        realName: "",
        phoneNumber: "",
        orgName: "",
      },
    };
  },
  methods: {
    etInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          this.userInfo = res.data.data;
        });
      });
    },
    /*
     * 搜索添加用户列表
     */
    dialoghandleFilter() {
      this.getDialogList();
    },
    rowClass({ row, rowIndex }) {
      return {
        padding: "5px 0",
        height: "20px",
        background: "rgba(247,247,248,1)",
      };
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件,确保只能选中一项数据
    select(selection, row) {
      this.$refs.multipleTable.clearSelection();
      if (selection.length === 0) return;
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    dialogHandleSelectionChange(arr) {
      this.dialogMultipleSelection = [];
      console.log("111", arr[arr.length - 1]);
      this.dialogMultipleSelection.push(arr[arr.length - 1]);
    },

    insertUser() {
      if (this.dialogMultipleSelection.length > 0) {
        this.dialogFormVisibleUser = false;
        this.userInfo = this.dialogMultipleSelection[0];
      } else {
        this.$message({
          message: "请选择用户！",
          type: "warning",
        });
      }
    },
    removeUser(item, index) {
      this.dialogMultipleSelection = [];
    },
    addUser() {
      for (const i in this.search) {
        this.search["" + i + ""] = "";
      }
      this.dialogListQuery.page = 1;
      this.dialogFormVisibleUser = true;
      this.getDialogList();
    },
    getDialogList(obj) {
      this.dialogListLoading = true;
      var query = {
        page: obj ? obj.page : this.dialogListQuery.page,
        pageSize: obj ? obj.limit : this.dialogListQuery.limit,
        userName: this.dialogsearch.userName,
        realName: this.dialogsearch.realName,
        phoneNumber: this.dialogsearch.phoneNumber,
        orgName: this.dialogsearch.orgName,
      };
      return new Promise((resolve, reject) => {
        getUserList(query)
          .then((response) => {
            console.log(response, "li");
            this.dialogList = response.data.data.rows;
            this.dialogTotal = response.data.data.total;
            this.dialogListLoading = false;
          })
          .catch((error) => {
            reject(error);
            this.dialogListLoading = false;
          });
      });
    },
    // 删除图片
    delInfoUrl(item, index) {
      this.infoUrlArr.splice(index, 1);
    },
    cropSuccess(resData) {
      this.imgcropIndexShow = false;
      this.imagecropperKey = this.imagecropperKey + 1;
      if (this.infoUrlArr.length == 3) {
        this.$message({
          message: "最多上传三张图片",
          type: "warning",
        });
        return;
      }
      this.infoUrlArr.push(resData[0].id);
      this.acceptInformationSupplement = this.infoUrlArr;
    },
    //是否受理
    agreeChange(value) {
      if (value == 4) {
        this.examineState = 0; //不受理
      } else {
        this.examineState = 1; //受理且本人

      }
    },
    //受理人是否为本人
    agreePeopleChange(value) {
      if (value == 0) {
        this.examineState = 1; //受理且本人
      } else {
        this.examineState = 2; //受理且非本人
      }
    },
    close() {
      this.imgcropIndexShow = false;
    },
    createData() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let postData = Object.assign({}, this.baseForm);
          const loading = this.$loading({
            lock: true,
            text: "请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.1)",
          });
          return new Promise((resolve, reject) => {
            SuggestActiveInsert(postData)
              .then(() => {
                loading.close();
                this.$notify({
                  title: "成功",
                  message: "创建成功",
                  type: "success",
                  duration: 1500,
                });
                this.$router.push({
                  path: "/reasonable/index",
                  name: "ReasonableMain",
                });
              })
              .catch((error) => {
                reject(error);
                loading.close();
              });
          });
        }
      });
    },
    getgo() {
      if (this.examineState == 2) {//2受理且非本人
        this.updateDatas();
      } else {
        this.updateData();//0不受理 1受理且本人
      }
    },
    //2受理且非本人--转至普通用户
    updateDatas() {
      if (this.dialogMultipleSelection.length == 0) {
        this.$message({
          message: "请选择受理人",
          type: "warning",
        });
        return;
      }
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let postData = Object.assign({}, this.baseForm);
          const loading = this.$loading({
            lock: true,
            text: "请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.1)",
          });
          let params = {
            id: this.baseForm.id,
            acceptUserId: this.userInfo.id,
            acceptPerson: this.userInfo.realName,
          };
          return new Promise((resolve, reject) => {
            acceptsnopersong(params)
              .then(() => {
                loading.close();

                this.$router.push({
                  path: "/reasonable/improveIndex",
                  name: "improveIndex",
                });
              })
              .catch((error) => {
                reject(error);
                loading.close();
              });
          });
        }
      });
    },
    
    //0不受理 1受理且本人
    updateData() {
      var ths = this
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let postData = Object.assign({}, this.baseForm);
          const loading = this.$loading({
            lock: true,
            text: "请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.1)",
          }); 
          var acceptStateui = 0
          var categoryui = ''
          if(this.baseForm.acceptState == 4){//0不受理
            acceptStateui = 4
            categoryui = ''
          }else{//1受理且本人
            categoryui = this.baseForm.category
            if (ths.baseForm.acceptSituation == '') {
              ths.$message({
                message: "请输入受理情况",
                type: "warning",
              });
              return;
            }
            if(ths.checkType == 'one'){
              acceptStateui = 3//受理完成
              if (ths.baseForm.publicity === '') {
                ths.$message({
                  message: "请选择是否公示",
                  type: "warning",
                });
                return;
              }
            }else{
              acceptStateui = 2//已受理待确认
            }
          }
          let params = {
            id: this.baseForm.id,
            acceptState: acceptStateui,
            reason: this.baseForm.reason || '',
            acceptUserId: this.userInfo.id,
            acceptPerson: this.userInfo.realName,
            acceptSituation: this.baseForm.acceptSituation || '',
            acceptInformationSupplement: this.acceptInformationSupplement.join() || '',
            category: categoryui,
          };
  
          return new Promise((resolve, reject) => {
            acceptisnoperson(params)
              .then(() => {
                loading.close();

                this.$router.push({
                  path: "/reasonable/improveIndex",
                  name: "improveIndex",
                });
              })
              .catch((error) => {
                reject(error);
                loading.close();
              });
          });
        }
      });
    },
    // 转至集团受理
    updateDatass() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let postData = Object.assign({}, this.baseForm);
          const loading = this.$loading({
            lock: true,
            text: "请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.1)",
          });
          let params = {
            id: this.baseForm.id,
            acceptState: 1,
          };
          return new Promise((resolve, reject) => {
            suggestPlanUpdates(params)
              .then(() => {
                loading.close();
                this.$router.push({
                  path: "/reasonable/improveIndex",
                  name: "improveIndex",
                });
              })
              .catch((error) => {
                reject(error);
                loading.close();
              });
          });
        }
      });
    },
    cancel() {
      this.$router.push({
        path: "/reasonable/improveIndex",
        name: "improveIndex",
      });
    },
  },
  created() {
   /* this.id = this.$route.query.id || "";
    this.acceptStates = this.$route.query.acceptState;
    this.checkType = this.$route.query.checkType;

    this.etInfo();
    if (this.id) {
      this.baseForm = JSON.parse(localStorage.getItem('rowData'))
      this.baseForm.acceptState = parseInt(this.baseForm.acceptState)
      console.log(this.baseForm)
      this.picture = this.baseForm.picture.split(",");
      this.state = "update";
    }*/
  }
}
</script>

<style lang="scss">
$mainColor: #18a5fd;

.el-select .el-input {
  width: 150px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

#workerStudyEdit {
  background-color: #fff;
  padding: 40px;
  padding-top: 20px;
  .main-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: "";
      position: absolute;
      width: 2px;
      background-color: $mainColor;
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }
  .dataForm {
    width: 800px;
    margin: 20px auto 0;
  }
  .common-btns {
    text-align: center;
  }
  .select-data {
    display: inline-block;
    background: rgba(246, 246, 246, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 0 10px;
    margin-right: 5px;
    i {
      cursor: pointer;
      padding-left: 5px;
    }
  }
  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    border: 1px dotted $mainColor;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: $mainColor;
    text-align: center;
    cursor: pointer;
  }
}
</style>
